package jz.joyoung.robot.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.TextUtils;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

import jz.joyoung.robot.util.Closeables;
import jz.joyoung.robot.util.LogUtil;

//import com.huawei.ecs.mtk.log.Logger;
//import com.huawei.groupzone.data.FileType;
//import com.huawei.log.TagInfo;

/**
 * This class is about file Tool class.
 */
public final class FileUtil {

    public static final String DEMO_TAG = "doctor_hyc";

    /**
     * 保存头像 bitmap.compress压缩
     *
     * @time 2019/8/26 14:12
     */
    public static File saveBitmap(Context context, Bitmap bitmap, String fileName) {
        File f = new File( context.getFilesDir().getPath(), fileName );
        if (f.exists()) {
            if (!f.delete()) {
                f.delete();
            }
        }
        try {
            FileOutputStream out = new FileOutputStream( f );
            bitmap.compress( Bitmap.CompressFormat.PNG, 100, out );
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return f;
    }

    /**
     * 把Bitmap转Byte
     */
    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress( Bitmap.CompressFormat.PNG, 100, baos );
        return baos.toByteArray();
    }

    //采样率压缩
    public static BitmapFactory.Options getBitmapOption(int inSampleSize) {
        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
    }


    /**
     * copy file
     *
     * @param input   FileInputStream
     * @param trgPath The path to the target file to be copied
     */
    public static boolean copyFile(InputStream input, String trgPath) {
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals( Environment.MEDIA_MOUNTED );
        if (!sdCardExist) {
            LogUtil.e( DEMO_TAG, "sdcard is not exist" );
            return false;
        }

        if (null == input || TextUtils.isEmpty( trgPath )) {
            LogUtil.e( DEMO_TAG, "stream or The target path is null!" );
            return false;
        }

        BufferedInputStream inBuffStream = null;
        FileOutputStream output = null;
        BufferedOutputStream outBuffStream = null;

        File trgFile = new File( trgPath );
        try {
            if (!trgFile.exists()) {
                boolean isCreateSuccess = trgFile.createNewFile();
                if (!isCreateSuccess) {
                    return false;
                }
            }
            inBuffStream = new BufferedInputStream( input );
            output = new FileOutputStream( trgFile );
            outBuffStream = new BufferedOutputStream( output );
            byte[] buffer = new byte[2 * 1024 * 1024];
            while (true) {
                int inBuflen = inBuffStream.read( buffer );
                if (-1 == inBuflen) {
                    outBuffStream.flush();
                    break;
                } else {
                    outBuffStream.write( buffer, 0, inBuflen );
                }
            }

            return true;
        } catch (FileNotFoundException e) {
            LogUtil.e( DEMO_TAG, e.getMessage() );
            return false;
        } catch (IOException e) {
            LogUtil.e( DEMO_TAG, e.getMessage() );
            return false;
        } finally {
            Closeables.closeCloseable( outBuffStream );
            Closeables.closeCloseable( output );
            Closeables.closeCloseable( inBuffStream );
            Closeables.closeCloseable( input );
        }
    }

    /**
     * is sdcard exist
     *
     * @return boolean
     */
    public static boolean isSdCardExist() {
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals( Environment.MEDIA_MOUNTED );
        if (sdCardExist) {
            return true;
        }
        LogUtil.e( DEMO_TAG, "sdcard is not exist" );
        return false;
    }

    public static void deleteFile(File file) {
        deleteFile( file, null );
    }

    public static void deleteFile(File file, File[] exceptFiles) {
        if (file == null || !file.exists()) {
            return;
        }

        if (file.isFile() && !file.isHidden()) {
            boolean success = file.delete();

            if (!success) {
                LogUtil.e( DEMO_TAG, "delete file error " );
            }

            return;
        }

        if (file.isDirectory() && !isContainFile( file, exceptFiles )) {
            File[] files = file.listFiles();
            if (null != files && 0 != files.length) {
                for (File f : files) {
                    deleteFile( f, exceptFiles );
                }
            }

            if (!file.delete()) {
                LogUtil.e( DEMO_TAG, "delete file error " );
            }
        }
    }

    /**
     * Unit conversion
     *
     * @param size
     * @return String
     */
    public static String makeUpSizeShow(double size) {
        double unit = 1024.0;
        String sizeUnit = "B";
        // to KB
        if (unit < size) {
            sizeUnit = "KB";
            size = size / unit;
        }
        // to M
        if (unit < size) {
            sizeUnit = "M";
            size = size / unit;
        }
        // to .00
        DecimalFormat df = new DecimalFormat( ".00" );
        return df.format( size ) + sizeUnit;
    }

    private static boolean isContainFile(File file, File[] files) {
        if (file == null || files == null || files.length == 0) {
            return false;
        }

        for (File f : files) {
            if (file.equals( f )) {
                return true;
            }
        }

        return false;
    }

    /**
     * 系统打开。
     *
     * @param gfFilePath
     * @return
     */
    public static int openBySystem(Context context, String gfFilePath) {
//        String mimeType = FileType.getMimeType(gfFilePath);
//        if (TextUtils.isEmpty(mimeType))
        {
//            Logger.debug(TagInfo.APPTAG, "mime type = " + mimeType);
            return OpenResult.OPEN_BY_THIRDPARTY_FAIL;
        }

//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.addCategory(Intent.CATEGORY_DEFAULT);

//        Uri uri = Uri.fromFile(com.huawei.utils.FileUtil.newFile(gfFilePath));
//        intent.setDataAndType(uri, mimeType);

//        try
//        {
//            context.startActivity(intent);
//            return OpenResult.OPEN_SUCCESS;
//        }
//        catch (ActivityNotFoundException e)
//        {
////            Logger.error(TagInfo.APPTAG, e.toString());
//            return OpenResult.OPEN_BY_THIRDPARTY_FAIL;
//        }
    }

    private interface OpenResult {
        int OPEN_SUCCESS = 0;
        int OPEN_BY_THIRDPARTY_FAIL = 1;
    }
}
